package com.woniuxy.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.entity.OSSUpdateResponseEntity;
import com.woniuxy.entity.utils.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;


@RestController
@RequestMapping("/oss")
public class OSSController {
    @Resource
    OSSClient ossClient;
    public static final String BUCKETNAME="woniuxy-92-htj";
    public static final String BASEURL="https://woniuxy-92-htj.oss-cn-hangzhou.aliyuncs.com/";

    @PostMapping("/update")
    public ResponseEntity update(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(BUCKETNAME,filename,inputStream);
        Date date = new Date(System.currentTimeMillis() + 1000 * 3600 * 24 * 60);
        URL url = ossClient.generatePresignedUrl(BUCKETNAME, filename, date);
        OSSUpdateResponseEntity ossUpdateResponseEntity = new OSSUpdateResponseEntity(filename, BASEURL+filename);
        return new ResponseEntity(ossUpdateResponseEntity);
    }

    @DeleteMapping("/del")
    public ResponseEntity del(String fileName){
        ossClient.deleteObject(BUCKETNAME,fileName);
        return ResponseEntity.SUCCESS;
    }
}
